import React, { useState, useEffect } from 'react';
import {
  FileExcelOutlined, SearchOutlined,CloudUploadOutlined,ToolOutlined,PlusSquareOutlined,ReloadOutlined
} from '@ant-design/icons';
import { Select, Button, Spin, Tabs, Modal } from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import * as XLSX from 'xlsx';

import {
  openNotification_util, fetchsync_util, useexcelauto,
  dealnullorundenfined,
  convertISODateTimeToYYYYMMDDHHMMSS,
  convertISODateTimeToYYYYMMDD
} from '../util/util.js'
var storage = window.localStorage;
const { Option } = Select;
import { use_gyspj_initcolmun, use_gyspj_initcolmun_import } from './use_gyszx_config.js';
import useStore from '../../useStore.js'
import { dropByCacheKey } from 'react-router-cache-route';
import ResizableTable from '../newmes/Resize_table_hook.js';

const IconFont = createFromIconfontCN({
  scriptUrl: 'http://111.77.154.58:2233/icon.js',
});

const Gyspj_list = () => {
  const history = useHistory();
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [isloading, setisloading] = useState(false)
  const [importloading, setimportloading] = useState(false)
  const [initSize, setinitSize] = useState() //table宽度大小
  const [ifshow, setifshow] = useState(true)
  const [listdata, setlistdata] = useState([])
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [excelData, setExcelData] = useState(null);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [columnarr, setcolumnarr] = useState(use_gyspj_initcolmun)
  const { nowroute, setnowroute, collapsed, setcollapsed } = useStore();
  const [listdata_gyskpmb, setlistdata_gyskpmb] = useState([])
  const [errorRows, setErrorRows] = useState([]);
  const [importError, setImportError] = useState([]);

  useEffect(() => {
    querylist()
    querylist_gyskpmb()
    storage[`Pc_gyspj_list_${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_gyspj_list_${storage.userid}`])) : setcolumnarr(columnarr)
    storage[`Pc_gyspj_list__initsize_${storage.userid}`] ? setinitSize(storage[`Pc_gyspj_list__initsize_${storage.userid}`]) : setinitSize(1)
  }, [])

  useEffect(() => { ifshow ? "" : setifshow(true) }, [ifshow])

  //路由跳转
  const tonormal = (route) => {
    history.push({ pathname: route });
  }

  const querylist = async () => {
    setisloading(true)
    storage[`Pc_gyspj_list_${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_gyspj_list_${storage.userid}`])) : setcolumnarr(columnarr)
    let rtdata = await fetchsync_util("/admin/gyszx/gyskplb", 'POST', {}, "json")
    // openNotification_util(rtdata.rtmessage)

    rtdata.resultdata.forEach(element => {
      element.create_time = convertISODateTimeToYYYYMMDDHHMMSS(element.create_time)
      element.kpzqq = element.kpzqq ? convertISODateTimeToYYYYMMDD(element.kpzqq) : ""
      element.kpzqz = element.kpzqz ? convertISODateTimeToYYYYMMDD(element.kpzqz) : ""
    });
    if (storage.yhlx == "租户用户") {
      rtdata.resultdata = rtdata.resultdata.filter(item => item.gysmc == storage.ygxm)
    }

    setlistdata(dealnullorundenfined(rtdata.resultdata))


    setselectedRowKeys([])
    setselectedRows([])
    setifshow(false)
    setisloading(false)
  }

  const querylist_gyskpmb = async () => {
    let rtdata = await fetchsync_util("/admin/gyszx/gyskpmb_lb", 'POST', {}, "json")
    setlistdata_gyskpmb(dealnullorundenfined(rtdata.resultdata))
  }

  /**
   * 手动查询
   */
  const handleQuery = async () => {
    querylist()
  }
  /**
   * 新增
   */
  const handleadd = async () => {
    storage.pre_gyspj_item = JSON.stringify({ data: {}, type: "add" })
    dropByCacheKey('gyspj_form')
    setnowroute({ ...{ route: "/shipSRM/gyszx/gyspj_form", title: "供应商评价_新增" } })
  }
  /**
   * 编辑
   */
  const handleEdit = async () => {
    if (selectedRows.length !== 1) {
      openNotification_util("须选中一条数据进行编辑!")
    }
    else {
      storage.pre_gyspj_item = JSON.stringify({ data: selectedRows[0], type: "edit" })
      dropByCacheKey('gyspj_form')
      setnowroute({ ...{ route: "/shipSRM/gyszx/gyspj_form", title: "供应商评价_编辑" } })
    }
  }
  /**
   * 删除
   */
  const handledelete = async () => {
    if (selectedRows.length !== 1) {
      openNotification_util("只可选择一条数据删除!")
    }
    else {
      let rtdata = await fetchsync_util("/admin/gyszx/delete_gyspj", 'POST', { selectedRows }, "json")
      rtdata.rtstatus ? querylist() : 1
    }
  }
  /**
   * 导出
   */
  const handleExport = async () => {
    let filtercol = use_gyspj_initcolmun_import().filter(item => item.show == true)
    filtercol.forEach(element => {
      element.width = element.width ? element.width / 7 : 10
    });
    useexcelauto(selectedRows.length>0?selectedRows:listdata, filtercol, '供应商评价')
  }


  /**
   * 导出标准模板
   */
  const handlegetmb = async () => {
    let filtercol = use_gyspj_initcolmun_import().filter(item => item.show == true)
    filtercol.forEach(element => {
      element.width = element.width ? element.width / 7 : 10
    });
    useexcelauto([], filtercol, '供应商评价_当前正式合作供应商名单')
  }

  const handleescelimport = async (data) => {
    let rtdata = await fetchsync_util("/admin/gyszx/gyskp_import", 'POST', {data}, "json")
    if (rtdata.resultdata.errorRows.length > 0) {
      setImportError(rtdata.resultdata.errorRows)
      setErrorRows([]);
    }
    else {
      setImportModalVisible(false);
      setImportError([]);
      setErrorRows([]);
      setExcelData(null);
      querylist()
    }
    openNotification_util("导入成功")
    setimportloading(false)
  }


  const handleView = async (data) => {
    storage.pre_gyspj_item = JSON.stringify({ data: data, type: "view" })
    dropByCacheKey('gyspj_form')
    setnowroute({ ...{ route: "/shipSRM/gyszx/gyspj_form", title: "供应商评价_查看" } })
  }

  const onImportExcel = (file) => {

    const { files } = file.target;
    const fileReader = new FileReader();
    fileReader.onload = event => {
      try {
        const { result } = event.target;
        const workbook = XLSX.read(result, { type: 'binary' });
        let data = []; // 存储获取到的数据
        for (const sheet in workbook.Sheets) {
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));

            // console.log("转化前的data 的格式及值为：",data)// break; // 如果只取第一张表，就取消注释这行
            // 将Excel中的数字格式日期转换为SQL Server可用的日期格式
            data = data.map(item => {
              if (item['考评周期止'] && typeof item['考评周期止'] === 'number') {
                const date = new Date((item['考评周期止'] - 25569) * 86400 * 1000);
                item['考评周期止'] = date.toISOString().split('T')[0];
              }
              if (item['考评周期起'] && typeof item['考评周期起'] === 'number') {
                const date = new Date((item['考评周期起'] - 25569) * 86400 * 1000);
                item['考评周期起'] = date.toISOString().split('T')[0];
              }
              if(item['按时交货率']){
                item['按时交货率'] = item['按时交货率']*100+"%"
              }
              if(item['批次合格率']){
                item['批次合格率'] = item['批次合格率']*100+"%"
              }
              return item;
            });
          }
        }
        var datastr = JSON.stringify(data);

        datastr = datastr.replace(/供应商名称/g, "gysmc").replace(/考评周期起/g, "kpzqq").replace(/考评周期止/g, "kpzqz")
        .replace(/批次合格率/g, "pchgl").replace(/检验合格批数/g, "jyhgps").replace(/总进料批数/g, "zjlps").replace(/制程异常次数/g, "zcyccs")
        .replace(/投诉次数/g, "tscs").replace(/质量得分/g, "zldf").replace(/按时交货率/g, "asjhl").replace(/按时交货批数/g, "asjhps")
        .replace(/总进料批数/g, "zjlps_jf")
        .replace(/交付得分/g, "jfdf").replace(/涨价次数/g, "zjcs").replace(/降价次数/g, "jjcs").replace(/价格得分/g, "jgdf")
        .replace(/异常反馈单逾期回复/g, "ycfk").replace(/供应商品质异常的处理时效性/g, "clsx").replace(/拖延，或拒绝退货和换货服务/g, "fw")
        .replace(/服务得分/g, "fwdf").replace(/总得分/g, "zdf");

        setExcelData(JSON.parse(datastr))
        console.log("=============datastr=================",datastr)
      } catch (e) {
        // 这里可以抛出文件类型错误不正确的相关提示
        console.log('文件类型不正确');
        return;
      }
    };
    // 以二进制方式打开文件
    fileReader.readAsArrayBuffer(files[0]);
  }





  const TabPaneItem = (title, listdata, columnarr, key) => {
    return <Tabs.TabPane tab={<span>{title} <span style={{
      display: 'inline-block', padding: '0 6px', fontSize: '12px', lineHeight: '14px', backgroundColor: '#a91f24',
      color: 'white', borderRadius: '8px', marginLeft: '4px'
    }}>{listdata.length}</span></span>}
      key={key}>
      {isloading ?
        (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>
          <Spin /></div>)
        :
        (<ResizableTable tabledata={listdata} tablecolnum={columnarr}
          width={collapsed ? "94%" : "84%"}
          storageName={`Pc_gyspj_list_${storage.userid}`}
          sfdoubleclick="false" ifhiddencchangeselecttype="true"
          selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
          showCz={{ showEdit: true, showView: true }}
          handleEdit={(data) => handleEdit(data, "edit")}
          handleView={(data) => handleEdit(data, "view")}
          handleDelete={(data, type) => handledelete(data, type)}
          defaultPageSize={10}
          bordered
          handleselectson={(selectedRows, selectedRowKeys) => {
            setselectedRows(selectedRows)
            setselectedRowKeys(selectedRowKeys)
          }}
        />)
      }
    </Tabs.TabPane>
  }

  return (
    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "4vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem",paddingRight:"1%"
    }}>



      <div style={styles.kshcontainer}>
        <div style={{
          width: "99vw", height: "", backgroundColor: "white", overflowX: "scroll", margin: "0.5vw",
          paddingLeft: "1vw",paddingRight:"1vw"
        }}>
          {storage.yhlx == "管理用户" &&
            <div style={styleobj.linestyleflex}>
                <ToolOutlined style={{ fontSize: "1rem", color: "#666666" }} />
                &nbsp;&nbsp;&nbsp;
              <span style={{ fontSize: "0.8rem", fontWeight: "500", color: "#666666" }}>工具栏</span>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
                onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleQuery() }}>
                <ReloadOutlined />刷新</Button>
                &nbsp;&nbsp;&nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
                onClick={handleadd}>
                <PlusSquareOutlined />新增</Button>
              &nbsp;&nbsp;&nbsp;
             <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleExport}>
              <FileExcelOutlined />导 出</Button>
              &nbsp;&nbsp;&nbsp;
              <Button style={{ backgroundColor: "#a91f24", color: "white", fontWeight: "800" }}
                onClick={() => setImportModalVisible(true)}>
                <CloudUploadOutlined /> 批量导入
              </Button>
              <Modal
              title="选择导入文件"
              visible={importModalVisible}
              onOk={() => {
                if (excelData && excelData.length > 0) {
                  handleescelimport(excelData);
                } else {
                  openNotification_util("请先选择并解析Excel文件");
                  setImportError([]);
                  setErrorRows([]);
                }
              }}
              onCancel={() => {
                setImportModalVisible(false);
                setImportError([]);
                setErrorRows([]);
                setExcelData(null);
              }}
            >
              {importloading ?
                (<div style={{ width: "90%", height: "", textAlign: "center", color: "#14d9cc" }}>
                  <Spin />
                  <div style={{ fontSize: "0.8rem", fontWeight: "500", color: "black" }}>导入中，请稍后...</div>
                  </div>)
                : (<>
                  <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
                    onClick={handlegetmb}>
                    <FileExcelOutlined /> 获取导入模板</Button>
                  <br />
                  <br />
                  <br />
                  <input
                    type='file'
                    accept='.xlsx, .xls'
                    onChange={(e) => {
                      onImportExcel(e);
                      e.target.value = null;
                    }}
                  />
                  {excelData && <div style={{ marginTop: 16 }}>已解析 {excelData.length} 条数据</div>}
                  {importError.length > 0 && (
                    <div style={{ marginTop: 16, color: 'red' }}>
                      以下行存在考评周期已存在供应商:
                      <ul>
                        {importError.map(err => (
                          <li key={err.rowNumber}>第{err.rowNumber}行考评周期：{err.kpzqq}到{err.kpzqz} 已存在供应商：{err.gysmc}</li>
                        ))}
                      </ul>
                    </div>
                  )}

                </>)
              }
            </Modal>
            </div>
          }

          {storage.yhlx == "租户用户" &&
            <div style={styleobj.linestyleflex}>
                <ToolOutlined style={{ fontSize: "1rem", color: "#666666" }} />
                &nbsp;&nbsp;&nbsp;
              <span style={{ fontSize: "0.8rem", fontWeight: "500", color: "#666666" }}>工具栏</span>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
                onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleQuery() }}>
                <ReloadOutlined />刷新</Button>
            </div>
          }
          <div style={{ width: "100%", height: "0.3vw", backgroundColor: "#F1F1F1" }}></div>
          <IconFont type="setting" style={{ position: 'absolute', right: '2vw', top: '1.2rem', fontSize: "1.5rem" }}
            onClick={e => setIsModalOpen(true)} />
          {isloading ?
            (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>
              <Spin /></div>)
            :
            (<ResizableTable tabledata={listdata} tablecolnum={columnarr}
              width={collapsed ? "94%" : "84%"}
              storageName={`Pc_gyspj_list_${storage.userid}`}
              czWidth={120}
              sfdoubleclick="false" ifhiddencchangeselecttype="true"
              selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
              showCz={storage.yhlx == "租户用户" ? { showView: true } : {  showView: true }}
              handleEdit={(data) => handleEdit(data, "edit")}
              handleView={(data) => handleView(data, "view")}
              // czMaps={{
              //   showEdit: { cz: '处理', handle: "handleEdit" },
              //   showView: { cz: '查看', handle: "handleView" },
              // }}
              defaultPageSize={10}
              bordered
              handleselectson={(selectedRows, selectedRowKeys) => {
                setselectedRows(selectedRows)
                setselectedRowKeys(selectedRowKeys)
              }}
            />)
          }

        </div>

      </div>
    </div>
  )
}


export default Gyspj_list


var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `#F1F1F1`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  butmainstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "8%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },


  kshcontainer: {
    width: "100%", minHeight: "40vh", position: "absolute", top: "2vh", left: "0vw", backgroundColor: "#F1F1F1",
    color: "black"
  },
}
var styleobj = {
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  linestylesmall: { height: "1.3rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },

  linestyleflex: {
    height: "1.8rem", fontSize: "0.6rem", position: "relative", width: "96vw", marginLeft: "0.1%",
    display: "flex", justifyContent: "flex-start", alignItems: "center", marginBottom: "0.5rem", marginTop: "0.5rem"
  },
  linestyleflexitem: {
    height: "1.6rem", fontSize: "0.7rem", position: "relative", width: "23%", textIndent: "0.5rem",
    backgroundColor: "white", lineHeight: "1.6rem", fontSize: "0.75rem", fontWeight: "500", textAlign: "center"
  },
  linestyleflexitemleft: { backgroundColor: "#F0F0F0", position: "absolute", width: "35%", left: "0" },
  linestyleflexitemright: { backgroundColor: "white", position: "absolute", width: "64%", right: "0" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", fontSize: "0.75rem", fontWeight: "700" },
}